<template>
  <view class="category-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text>加载中...</text>
    </view>
    <!-- 错误状态 -->
    <view v-else-if="error" class="error-container">
      <text class="error-text">{{ errorMessage }}</text>
      <button class="retry-btn" @tap="loadCategory">重试</button>
    </view>
    <!-- 过期状态 -->
    <view v-else-if="expired" class="expired-container">
      <text class="expired-text">分享链接已过期</text>
    </view>
    <!-- 分类内容 -->
    <view v-else class="category-content">
      <view class="category-header">
        <text class="category-title">{{ category.name || category.categoryTitle }}</text>
        <view class="category-meta">
          <text class="category-count">{{ articles.length }}个案例</text>
          <text class="category-views">{{ category.views || 0 }}次浏览</text>
        </view>
      </view>
      <view v-if="category.description" class="category-desc">
        <text>{{ category.description }}</text>
      </view>
      <view class="article-list">
        <view 
          v-for="(item, index) in articles" 
          :key="index" 
          class="article-item"
          @tap="goDetail(item)"
        >
          <image 
            v-if="getCoverImage(item.litpic)" 
            :src="getCoverImage(item.litpic)" 
            mode="aspectFill" 
            class="article-cover"
          ></image>
          <view v-else class="article-cover no-image">
            <text>暂无图片</text>
          </view>
          <view class="article-info">
            <text class="article-title">{{ item.title }}</text>
            <view class="article-meta">
              <text class="article-date">{{ formatDate(item.createTime) }}</text>
              <text class="article-views">{{ item.views || 0 }}次浏览</text>
            </view>
          </view>
        </view>
        <view v-if="articles.length === 0" class="empty-state">
          <text class="empty-text">暂无内容</text>
        </view>
      </view>
      <view class="share-tip">此内容由他人分享给您</view>
    </view>
  </view>
</template>

<script>
import { shareApi } from '@/api/config';
import { getFullImageUrl } from '@/utils/image';
import templateService from '@/utils/template';
import { preprocessArticles } from '@/utils/templateData';

export default {
  data() {
    return {
      token: '',
      category: {},
      articles: [],
      details: {},
      loading: true,
      error: false,
      errorMessage: '',
      expired: false,
      showDetail: false,
      detailContent: '',
      detailTitle: '',
      listTemplate: '',
      renderedTemplate: '',
      templateLoadStatus: {
        success: false,
        message: ''
      }
    };
  },
  onLoad(options) {
    this.token = options.token || '';
    if (!this.token) {
      this.error = true;
      this.errorMessage = '参数错误，无法加载内容';
      this.loading = false;
      return;
    }
    this.loadCategory();
  },
  // 添加页面配置，支持微信小程序右上角分享
  mpType: 'page',
  onShareAppMessage() {
    return {
      title: this.category.name || this.category.categoryTitle || '栏目分享',
      path: `/pages/shared/category?token=${this.token}`
    };
  },
  onShareTimeline() {
    return {
      title: this.category.name || this.category.categoryTitle || '栏目分享',
      query: `token=${this.token}`,
      imageUrl: this.getCoverImage(this.articles[0]?.litpic) || ''
    };
  },
  methods: {
    async loadCategory() {
      this.loading = true;
      this.error = false;
      try {
        // 只调用 getCategoryContents 接口
        const listRes = await shareApi.getCategoryContents(this.token);
        // category-contents接口返回结构为 {contents: [...], details: {...}, category: {...}}
        this.articles = preprocessArticles((listRes.code === 200 && listRes.data && Array.isArray(listRes.data.contents)) ? listRes.data.contents : []);
        this.details = (listRes.code === 200 && listRes.data && listRes.data.details) ? listRes.data.details : {};
        this.category = (listRes.code === 200 && listRes.data && listRes.data.category) ? listRes.data.category : {};
        // 新增：加载模板
        if (this.category) {
          await this.loadTemplate(this.category);
          this.renderTemplate();
        }
      } catch (error) {
        this.error = true;
        this.errorMessage = '网络错误，请重试';
      } finally {
        this.loading = false;
      }
    },
    async loadTemplate(category) {
      try {
        this.templateLoadStatus = {
          success: false,
          message: '正在加载模板...'
        };
        this.listTemplate = await templateService.getCategoryListTemplate(category);
        if (this.listTemplate) {
          this.templateLoadStatus.success = true;
          this.templateLoadStatus.message = '模板加载成功';
        } else {
          this.templateLoadStatus.message = '模板加载失败或为空';
        }
      } catch (e) {
        this.templateLoadStatus.message = '模板加载异常';
      }
    },
    renderTemplate() {
      if (!this.listTemplate) {
        this.renderedTemplate = '';
        return;
      }
      // 扁平化数据结构，便于 mustache 渲染
      const templateData = {
        ...(this.category || {}),
        articles: this.articles
      };
      const rendered = templateService.parseTemplate(this.listTemplate, templateData);
      if (rendered) {
        this.renderedTemplate = rendered;
      } else {
        this.renderedTemplate = '';
      }
    },
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    getCoverImage(litpic) {
      if (!litpic) return '';
      try {
        let imgs = litpic;
        if (typeof litpic === 'string') {
          imgs = JSON.parse(litpic);
        }
        if (Array.isArray(imgs) && imgs.length > 0) {
          let url = imgs[0].url || imgs[0];
          return getFullImageUrl(url);
        }
      } catch (e) { return ''; }
      return '';
    },
    showArticleDetail(item) {
      const detail = this.details[item.id];
      this.detailTitle = item.title;
      this.detailContent = detail && detail.content ? detail.content : '';
      this.showDetail = true;
    },
    closeDetail() {
      this.showDetail = false;
      this.detailContent = '';
      this.detailTitle = '';
    },
    goDetail(item) {
      uni.navigateTo({
        url: `/pages/detail/sharedetail?id=${item.id}`
      });
    }
  }
};

</script>

<style lang="scss" scoped>
.category-container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #fff;
}
.loading-container, .error-container, .expired-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 80vh;
}
.error-text, .expired-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}
.retry-btn {
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  font-size: 28rpx;
  color: #fff;
  background-color: #007aff;
  border-radius: 35rpx;
}
.category-content {
  padding-bottom: 100rpx;
}
.category-header {
  margin-bottom: 30rpx;
}
.category-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  margin-bottom: 20rpx;
}
.category-meta {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}
.category-count {
  margin-right: 20rpx;
}
.category-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}
.article-list {
  margin-bottom: 40rpx;
}
.article-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
}
.article-cover {
  width: 200rpx;
  height: 150rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}
.no-image {
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.no-image text {
  font-size: 24rpx;
  color: #999;
}
.article-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.article-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.article-meta {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  color: #999;
}
.article-date {
  margin-right: 20rpx;
}
.empty-state {
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.empty-text {
  font-size: 28rpx;
  color: #999;
}
.share-tip {
  margin-top: 40rpx;
  text-align: center;
  color: #999;
  font-size: 26rpx;
}
</style> 